package test.annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Arrays;

import com.sun.xml.internal.bind.v2.schemagen.xmlschema.List;

public class APICreate {
	public static SeverAPI create(Class<SeverAPI> api) {
		SeverAPI apiProxy = (SeverAPI) Proxy.newProxyInstance(api.getClassLoader(), new Class[] {api}, new InvocationHandler() {
			
			@Override
			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
				// TODO Auto-generated method stub
				getMethodMsg(method,args);
				SeverAPI obj = getAPI();
				return method.invoke(obj, args);
			}
		});
		return apiProxy;
	}
	
	private static SeverAPI getAPI() {
        return new SeverAPI() {
            @Override
            public String getBaiduHome(String type) {
                return "I am getBaiduHome return by proxy";
            }

			@Override
			public String getBaiduUser(String name) {
				// TODO Auto-generated method stub
				return "I am getBaiduUser return by proxy";
			}
        };
    }

	
	public static void getMethodMsg(Method method,Object[] args) {
		AnnoBean bean = new AnnoBean();
		bean.setMethodName(method.getName());
		Annotation[] annotations = method.getAnnotations();
		for(Annotation annotation : annotations) {
			if(annotation instanceof Get) {
				Get get = (Get)annotation;
				String value = get.value();
				bean.setMethodAnniType("Get");
				bean.setMethodAnniValue(value);
			}
			if(annotation instanceof Post) {
				Post post = (Post)annotation;
				String value = post.value();
				bean.setMethodAnniType("Post");
				bean.setMethodAnniValue(value);
			}
		}
		bean.setArgs(Arrays.asList(args));
		Annotation[][] parameterAnnotations = method.getParameterAnnotations();
		for(Annotation[] annotation : parameterAnnotations) {
			for(Annotation annotation1 : annotation) {
				if(annotation1 instanceof Query) {
					bean.setQuery(((Query) annotation1).name());
				}
			}
		}
		System.out.println(bean.toString());
	}

}
